<script>
	'use strict';

	var amapFile = require('././utils/amap-wx.js'); //高德
	// var QQMapWX  = require('././utils/qqmap-wx-jssdk.min.js');//腾讯
	import globalData from "./globalData.js";
import {
	scanCodeFn
} from "./utils/scanCode.js";
import {
	isWeiXin
} from '@/utils/h5.js';
import {
	getActivityCityId
} from '@/api/marketing/invitation';
	var util_1 = require("./utils/util");
	var debounce = new util_1.Debounce();
	var debounce2 = new util_1.Debounce(); //信号弱
	var https_1 = require('././api/https.js'); // <IAppOption>
	var pc_1 = require("./api/pc/pc");
	export default {
		data() {

		},
		globalData: {
			...globalData,
			// 登录函数
			//   login: function (callback: any) {
			//     const $this = this
			//     wx.login({
			//       success: (res: any) => {
			//         if (res.code) {
			//           getJsCode2session({
			//             sellerId: $this.globalData.sellerId,
			//             jsCode: res.code
			//           }).then((res: any) => {
			//             if (res.code == 0) {
			//               $this.globalData.openId = res.data.openid
			//               $this.globalData.unionId = res.data.unionid
			//               $this.globalData.session_key = res.data.session_key
			//               callback && callback(res.data.openid, res.data.session_key)
			//             } else {
			//               wx.showModal({
			//                 title: '消息提示',
			//                 content: '获取配置信息失败，请联系商家管理员！',
			//                 confirmText: '确定',
			//                 showCancel: false,
			//               })
			//             }
			//           })
			//         }
			//       }
			//     })
			//   },
			CHECK_LOGIN: function(callback) {
				var token = uni.getStorageSync('token');

				if (token) {
					if (callback) {
						callback();
					}
				} else {
					uni.showToast({
						title: '请先进行登录!',
						icon: 'none'
					});
					setTimeout(function() {
						console.log('去登录咯CHECK_LOGIN!!!')
						let pages = getCurrentPages()
						const loginUrl = "packagePersonal/pages/login/login"
						if (!(getCurrentPages()[pages.length - 1].route == loginUrl)) {
							uni.navigateTo({
								url: `/${loginUrl}`,
							});
						} else {
							console.log('已经是登录页面了CHECK_LOGIN')
						}
					}, 2500)
				}
			},

			// 提示
			CHECK_LOGIN_Toast: function(callback, tips) {
				var token = uni.getStorageSync('token');
				if (token) {
					if (callback) {
						callback();
					}
				} else {
					uni.showToast({
						title: tips,
						icon: 'none'
					});
					setTimeout(function() {
						let pages = getCurrentPages()
						const loginUrl = "packagePersonal/pages/login/login"
						if (!(getCurrentPages()[pages.length - 1].route == loginUrl)) {
							uni.navigateTo({
								url: `/${loginUrl}`,
							});
						} else {
							console.log('已经是登录页面了CHECK_LOGIN')
						}
					}, 2500)
				}
			},
			// 跳转登录页 可取消
			CHECK_LOGIN_Model: function(callback, tips) {
				var token = uni.getStorageSync('token');
				if (token) {
					if (callback) {
						callback();
					}
				} else {
					uni.showModal({
						title: '温馨提示',
						content: tips,
						confirmText: '登录',
						success: (res) => {
							if (res.confirm) {
								console.log('用户点击确定');
								uni.navigateTo({
									url: '/packagePersonal/pages/login/login'
								});
							}

						}
					});
				}
			},

			// 直线距离 返回千米
			getFlatternDistance: function(lat1, lng1, lat2, lng2) {
				if (lat1 === lat2 && lng1 === lng2) {
					return 0;
				}

				var PI = Math.PI;
				var EARTH_RADIUS = 6378137;

				function getRad(d) {
					return (d * PI) / 180;
				}

				var f = getRad((lat1 + lat2) / 2);
				var g = getRad((lat1 - lat2) / 2);
				var l = getRad((lng1 - lng2) / 2);
				var sg = Math.sin(g);
				var sl = Math.sin(l);
				var sf = Math.sin(f);
				var s;
				var c;
				var w;
				var r;
				var d;
				var h1;
				var h2;
				var a = EARTH_RADIUS;
				var fl = 1 / 298.257;
				sg = sg * sg;
				sl = sl * sl;
				sf = sf * sf;
				s = sg * (1 - sl) + (1 - sf) * sl;
				c = (1 - sg) * (1 - sl) + sf * sl;
				w = Math.atan(Math.sqrt(s / c));
				r = Math.sqrt(s * c) / w;
				d = 2 * w * a;
				h1 = (3 * r - 1) / 2 / c;
				h2 = (3 * r + 1) / 2 / s;
				var distance = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
				return (distance / 1000).toFixed(2);
			},

			//获取token
			getToken: function() {
				var _this = this;

				var that = this;
				var tel = uni.getStorageSync('tel');
				var openId = uni.getStorageSync('openid');
				const unionId = uni.getStorageSync('unionId');
				const token = uni.getStorageSync('token');
				// if (!openId) {
				https_1
					.getToken({
						phoneNo: tel,
						sourceType: '0',
						sellerNo: that.sellerNo
					})
					.then(function(res) {
						uni.setStorageSync('token', res.data);
						uni.switchTab({
							url: '/pages/index/index'
						});
					});
				// }
			},

			// 检测新版本
			updateManager: function() {
				var updateManager = uni.getUpdateManager();
				updateManager.onUpdateReady(function() {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，是否重启应用？',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								updateManager.applyUpdate();
							}
						}
					});
				});
			},

			//获取当前城市Id
			getCityId: function(callback) {
				let cityName = uni.getStorageSync('cityName') || uni.getStorageSync('currentCityName');
				getActivityCityId(cityName).then(res => {
					console.log('查询城市id（活动）', res.data)
					uni.setStorageSync('cityId1', res.data)
				})
				// #ifdef APP-PLUS
				https_1.citareaListByNamey({
					name: cityName,
				}).then((res) => {
					if (res.code == 0) {
						if (uni.getStorageSync('currentCityName') && !uni.getStorageSync(
								'currentCityId')) {
							uni.setStorageSync('currentCityId', res.data.id);
						}
						uni.setStorageSync('cityId', res.data.id);
						this.setMemberPersonalData(res.data.id)
						// uni.setStorageSync('latitude', res.data.latitude);
						// uni.setStorageSync('longitude', res.data.longitude);
						callback && callback()
					}
				})
				return
				// #endif
				if (cityName) {
					https_1.citareaListByNamey({
						name: cityName,
					}).then((res) => {
						if (res.code == 0) {
							if (uni.getStorageSync('currentCityName') && !uni.getStorageSync(
									'currentCityId')) {
								uni.setStorageSync('currentCityId', res.data.id);
							}
							uni.setStorageSync('cityId', res.data.id);
							this.setMemberPersonalData(res.data.id)
							// uni.setStorageSync('latitude', res.data.latitude);
							// uni.setStorageSync('longitude', res.data.longitude);
							callback && callback()
						}
					})
				} else {
					this.getCity(callback);
				}
			},
			count: 0,
			// 设置地区
			setMemberPersonalData(areaId) {
				if (uni.getStorageSync('token')) {
					https_1.getMemberPersonalData().then(res => {
						if (res.code == 0) {
							let data = res.data
							if (!data.areaId) {
								data.areaId = areaId
								https_1.updateMemberPersonalData(data).then(res => {
									console.log(res, '设置定位成功')
								})
							}
						}
					})
					let cityName = uni.getStorageSync('cityName') || uni.getStorageSync('currentCityName')
					getActivityCityId(cityName).then(res => {
						console.log('查询城市id（活动）', res.data)
						uni.setStorageSync('cityId1', res.data)
					})
				}
			},
			// 获取当前城市名-高德
			getCity: function(callback, type = false, isTip = false) {
				var that = this;
				// callback()
				var myAmapFun = new amapFile.AMapWX({
					key: that.mapkey,
				});
				myAmapFun.getRegeo({
					success: function(res) {
						let geoCityname = Array.isArray(res[0].regeocodeData.addressComponent.city) ?
							res[0].regeocodeData.addressComponent.province :
							res[0].regeocodeData.addressComponent.city;
						console.log('定位成功，获取定位城市名称===>', geoCityname)
						that.cityname = geoCityname;
						that.currentCity.cityName = geoCityname;
						that.currentCity.latitude = res[0].latitude;
						that.currentCity.longitude = res[0].longitude; //授权成功之后---------->当前城市的经纬度

						// 可以拿到用户当前准确的定位
						uni.setStorageSync('currentCityName', geoCityname);
						uni.setStorageSync('cityName', geoCityname);
						uni.setStorageSync('latitude', res[0].latitude);
						uni.setStorageSync('longitude', res[0].longitude);

						// if(!isUserLocal){
						// 	that.userLocalStatus = 0;
						// }

						that.userLocalStatus = 0;

						that.getCityId(callback);
					},
					fail: function(err) {
						uni.setStorageSync('latitude', globalData.defaultCity.latitude);
						uni.setStorageSync('longitude', globalData.defaultCity.longitude);
						console.log("定位失败", err);
						// if(err.errMsg.indexOf('wx.onLocationChange') > 0) {
						//     setTimeout(() => {
						//         that.getCityId(callback)
						//     }, 3000)
						// } else {
						// if(!isTip) return 
						console.log('that.isLocationAlear', that.isLocationAlear)
						// if(that.isLocationAlear) return;
						that.isLocationAlear = true;
						try {
							const res = uni.getSystemInfoSync()
							let env = uni.getSystemInfoSync().platform;
							if (env === "android" || env === "ios") {
								console.log('走到这里安卓的', that.defaultCity.cityName)
								that.cityname = that.defaultCity.cityname;
								that.currentCity.cityName = that.defaultCity.cityName;
								that.currentCity.latitude = that.defaultCity.latitude;
								that.currentCity.longitude = that.defaultCity
									.longitude; //授权成功之后---------->当前城市的经纬度

								uni.setStorageSync('currentCityName', that.defaultCity.cityName);
								uni.setStorageSync('latitude', that.defaultCity.latitude);
								uni.setStorageSync('longitude', that.defaultCity.longitude);
								that.userLocalStatus = 0;

								that.getCityId(callback);
							}
							// else if (env === "ios") {
							// if (permision.judgeIosPermission("location")){
							//     // 信号弱
							//     that.userLocalStatus = 2;
							//     callback && callback()
							//     uni.showModal({
							//         title: '定位服务信号弱',
							//         content: '当前手机定位信号较弱， 请移动到空旷处再尝试！',
							//         confirmText: '重新获取',
							//         confirmColor: '#1487FA',
							//         success: function(res) {
							//             that.isLocationAlear = false;
							//             if (res.confirm) {
							//                 that.getCity(callback);
							//             }
							//         }
							//     });
							// } else {
							//     // 未授权
							//     that.userLocalStatus = 1;
							//     callback && callback()
							//     uni.showModal({
							//         title: '定位服务未开启',
							//         content: '请开启手机定位服务或选择当前城市 以获取周边充电站信息！',
							//         confirmText: '好的',
							//         confirmColor: '#1487FA',
							//         cancelText: '暂不选择',
							//         success: function(res) {
							//             that.isLocationAlear = false;
							//             if (res.confirm) {
							//                 that.CHECK_LOGIN(function() {
							//                     uni.navigateTo({
							//                         url: '/homeSub/pages/area/area'
							//                     });
							//                 });
							//             } else if(res.cancel) {
							//                 if(getCurrentPages()[getCurrentPages().length - 1].route == 'pages/site/index') {
							//                     uni.reLaunch({
							//                         url: '/pages/index/index'
							//                     })
							//                 }
							//             }
							//         }
							//     });
							// }
							// }
							else {
								if (!res.locationEnabled) {
									that.userLocalStatus = 1;
									callback && callback()
									uni.showModal({
										title: '定位服务未开启',
										content: '请开启手机定位服务或选择当前城市 以获取周边充电站信息！',
										confirmText: '好的',
										confirmColor: uni.getStorageSync('textColor') || '#6DB12E',
										cancelText: '暂不选择',
										success: function(res) {
											that.isLocationAlear = false;
											if (res.confirm) {
												if (!type) {
													// that.CHECK_LOGIN(function() {
													uni.navigateTo({
														url: '/homeSub/pages/area/area'
													});
													// });
												}
											} else if (res.cancel) {
												if (getCurrentPages()[getCurrentPages()
														.length - 1].route ==
													'pages/site/index') {
													uni.reLaunch({
														url: '/pages/index/index'
													})
												}
											}
										}
									})
								} else {
									uni.getSetting({
										success: function(res) {
											if (!res.authSetting['scope.userLocation']) {
												// 未授权
												that.userLocalStatus = 1;
												callback && callback()
												uni.showModal({
													title: '定位服务未开启',
													content: '请开启手机定位服务或选择当前城市 以获取周边充电站信息！',
													confirmText: '好的',
													confirmColor: uni.getStorageSync(
														'textColor') || '#6DB12E',
													cancelText: '暂不选择',
													success: function(res) {
														that.isLocationAlear =
															false;
														if (res.confirm) {
															if (!type) {
																// that.CHECK_LOGIN(function() {
																uni.navigateTo({
																	url: '/homeSub/pages/area/area'
																});
																// });
															} else {
																uni.openSetting({
																	success(
																		res
																	) {
																		if (res[
																				'scope.userLocation'
																			]) {
																			console
																				.log(
																					res
																					.authSetting,
																					'授权地理位置拉'
																				)
																			that.getCity(
																				callback
																			);
																		}
																	}
																})
															}
														} else if (res.cancel) {
															if (getCurrentPages()[
																	getCurrentPages()
																	.length - 1]
																.route ==
																'pages/site/index'
															) {
																uni.reLaunch({
																	url: '/pages/index/index'
																})
															}
														}
													}
												});
											} else {
												// 【2024-08-06】临时处理方案：如果高德地图获取定位失败，就是用 uni.getLocation 获取定位，不弹出弹窗提示
												that.userLocalStatus = 0
												callback && callback()
												// uni.getLocation({
												// 	type: 'wgs84',
												// 	// type: 'gcj02',
												// 	isHighAccuracy: true,
												// 	success: (gpsRes) => {
												//    // 只有app 可以拿到城市的相关信息
												// 		console.log('----gpsRes----',  gpsRes);
												// 		uni.setStorageSync('latitude', gpsRes.latitude);
												// 		uni.setStorageSync('longitude', gpsRes.longitude);
												// 	},
												// 	fail: (gpsErr) => {
												// 		console.error('----gpsErr----',  gpsErr);
												// 	}
												// })

												// ========== 【2024-08-06】暂时注释，因为高德的key 无法使用 ===========
												// 信号弱
												// that.userLocalStatus = 2;
												// callback && callback()
												// uni.showModal({
												// 	title: '定位服务信号弱',
												// 	content: '当前手机定位信号较弱， 请移动到空旷处再尝试！',
												// 	confirmText: '重新获取',
												// 	confirmColor: uni.getStorageSync('textColor') || '#6DB12E',
												// 	success: function(res) {
												// 		that.isLocationAlear = false;
												// 		if (res.confirm) {
												// 			that.getCity(callback);
												// 		}
												// 	}
												// });
											}
										}
									});
								}
							}
						} catch (e) {}
						// }
					}
				});
			}
		},
		onLaunch: function(options) {
			// #ifdef MP-ALIPAY
			// console.error("获取二维码地址~~~~onLaunch~~~~~~", JSON.stringify(options))
			if (options.query) {
				var url = decodeURIComponent(options.query.qrCode);
				// console.error("获取二维码地址~~url~~~~~~~", url)
				if (url.indexOf("?") != -1) {
					uni.setStorageSync('openQrcodeUrl', url)
				}
			}
			/**
			 * 模拟数据
			 const url = "https://hccn.info/codeFusion/#/gunnoList?connectorID=81002837&sellerNo=tjhz&token=2440a47610920cb7afd24c5bf990bda0&type=test"
			 console.error("打印数据~~url~~~~~~~", url.indexOf("?") != -1)
			 if (url.indexOf("?") != -1) {
			 	console.error("发送数据===================")
			 	uni.setStorageSync('openQrcodeUrl', url)
			 }
			 */

			// #endif

			let sellerNo = this.globalData.sellerNo
			if (this.isChangzhi()) {
				// 微信公众号请求openid
				this.getWxGzhOpenid()
			}
			// 小程序内嵌h5处理
			this.setMiniInH5()

			// App内嵌H5处理
			this.setAppInH5()
			uni.setStorageSync('defaultColor_Green', '#6DB12E')
			uni.removeStorageSync('currentCityId');
			uni.removeStorageSync('currentCityName');
			uni.removeStorageSync('cityId');
			uni.removeStorageSync('cityName');
			uni.removeStorageSync('latitude');
			uni.removeStorageSync('longitude');

			uni.setStorageSync('ApiUrl', this.globalData.URL);
			uni.setStorageSync('imgUrl', this.globalData.imgUrl);
			uni.setStorageSync('marketingApiUrl', this.globalData.marketingUrl);
			uni.setStorageSync('PCURL', this.globalData.PCURL);
			uni.setStorageSync('sellerNo', this.globalData.sellerNo);
			// this.setNavBarHeight()
			// #ifdef MP-WEIXIN
			this.uniLogin();
			// #endif

			// #ifdef MP-ALIPAY
			this.uniALiPayLogin();
			// #endif

			uni.hideTabBar({});
		},
		onShow: function() {
			this.globalData.updateManager();
			// #ifdef MP-WEIXIN
			wx.onMemoryWarning(function() {
				console.log('请注意：内存不足！！')
				//   wx.clearStorage()
			})
			// #endif
		},
		methods: {
			showLoading: util_1.showLoading,
			hideLoading: util_1.hideLoading,

			// 支付宝小程序登录处理
			uniALiPayLogin() {
				const that = this;
				return new Promise((resolve, reject) => {
					uni.getProvider({
						service: 'oauth',
						success: function(res) {
							if (~res.provider.indexOf('alipay')) {
								uni.login({
									provider: 'alipay',
									onlyAuthorize: true,
									success: function(loginRes) {
										let {
											sellerId
										} = that.globalData;
										https_1.getJsCode2session({
											sellerId,
											jsCode: loginRes.code,
											type: 7
										}).then(info => {
											if (info.code == 0) {
												let obj = {
													openid: info.data.open_id,
													firstRegister: info.data
														.firstRegister,
													newMember: info.data
														.newMember
												}
												uni.setStorageSync("openId",
													obj.openid);
												uni.setStorageSync("firstRegister",
													obj.firstRegister);
												// 整改优化添加判断是否新用户
												uni.setStorageSync("newMember",
													obj.newMember);
												resolve(obj)
											} else {
												reject()
												uni.showModal({
													title: '消息提示',
													content: '获取配置信息失败，请联系商家管理员！',
													confirmText: '确定',
													showCancel: false,
												})
												if (getCurrentPages()[
														getCurrentPages().length -
														1].route !==
													'pages/errorPage/index') {
													uni.navigateTo({
														url: '/pages/errorPage/index?code=500'
													});
												}
											}
										}).catch(err => {
											reject(err)
										})
									},
									fail(err) {
										console.log(err, 'loginError')
										reject(err)
									}
								})
							}
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},

			uniLogin() {
				const that = this;
				return new Promise((resolve, reject) => {
					uni.getProvider({
						service: 'oauth',
						success: function(res) {
							if (~res.provider.indexOf('weixin')) {
								uni.login({
									provider: 'weixin',
									onlyAuthorize: true,
									success: function(loginRes) {
										let {
											sellerId
										} = that.globalData;
										https_1.getJsCode2session({
											sellerId,
											jsCode: loginRes.code
										}).then(info => {
											if (info.code == 0) {
												let {
													openid,
													unionid,
													session_key,
													firstRegister,
													newMember
												} = info.data;
												uni.setStorageSync("openId",
													openid);
												uni.setStorageSync("unionId",
													unionid);
												uni.setStorageSync('session_key',
													session_key);
												uni.setStorageSync("firstRegister",
													firstRegister);
												// 整改优化添加判断是否新用户
												uni.setStorageSync("newMember",
													newMember);
												resolve({
													openid,
													unionid,
													session_key,
													firstRegister,
													newMember
												})
												// that.globalData.openId = openid
												// that.globalData.unionId = unionid
												// that.globalData.session_key = session_key
											} else {
												reject()
												uni.showModal({
													title: '消息提示',
													content: '获取配置信息失败，请联系商家管理员！',
													confirmText: '确定',
													showCancel: false,
												})
												if (getCurrentPages()[
														getCurrentPages().length -
														1].route !==
													'pages/errorPage/index') {
													uni.navigateTo({
														url: '/pages/errorPage/index?code=500'
													});
												}
											}
										}).catch(err => {
											reject(err)
										})
									},
									fail(err) {
										reject(err)
										console.log(err, 'loginError')
									}
								})
							}
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			setNavBarHeight: function(options) {
				var _this = this;
				var _this = this;
				//自定义导航栏 获取设备顶部窗口的高度（不同设备窗口高度不一样，根据这个来设置自定义导航栏的高度）
				uni.getSystemInfo({
					success: function(res) {
						var custom = uni.getMenuButtonBoundingClientRect();
						_this.globalData.statusBarHeight = res.statusBarHeight;
						_this.globalData.navBarHeight = custom.height + (custom.top - res
							.statusBarHeight) * 2;
					}
				});
			},
			// 判断页面路径是否为标签栏
			isTabPath: function(path) {
				var pages = getCurrentPages();
				var tabsPath = [
					"pages/index/index",
					"pages/site/index",
					"pages/find/index",
					"pages/my/my"
				];
				if (pages.length) {
					var prevPage = pages[pages.length - 1];
					var pagePath = path || prevPage.route;
					return tabsPath.includes(pagePath);
				}
				return false;
			},
			// 设置全局的optionsQuery 并且返回设置的结果
			setOptionsQuery: function(query) {
				//判断query.scene是否存在 存在的话就是扫小程序二维码进来的要将scene反编译转成对象形式然后赋值给query
				if (query.scene && JSON.stringify(query.scene) != '{}') {
					var queryOptions_1 = {};
					var queryStr = decodeURIComponent(query.scene); //转换成格式'a=1&b=2'
					// 装换成对象
					queryStr.split('&').forEach(function(item) {
						var data = item.split('=');
						queryOptions_1[data[0]] = data[1];
					});
					query = queryOptions_1;
				}
				// 判断query存在吗存在的话赋值给全局的optionsQuery
				if (query && JSON.stringify(query) != '{}') {
					this.globalData.optionsQuery = query;
				}
				// 返回处理过的query
				return query;
			},
			// 获取全局的OptionsQuery的字符串形式 将格式{a:1,b:2} 转换成 '?a=1&b=2'
			getOptionsQuery: function(options) {
				var query = options || this.globalData.optionsQuery || {};
				var str = [];
				var queryStr = '';
				for (var p in query) {
					if (query[p]) {
						str.push(p + "=" + query[p]);
					}
				}
				queryStr = str.join("&");
				if (queryStr) {
					return '?' + queryStr;
				}
				return queryStr;
			},
			// 设置并且获取全局的OptionsQuery
			getAppOptions: function(query) {
				query = query || this.globalData.optionsQuery;
				return this.setOptionsQuery(query);
			},
			// 删除全局的OptionsQuery
			removeOptionsQuery: function() {
				this.globalData.optionsQuery = {};
			},

			// 获取版本
			getEnvVersion() {
				// 返回微信小程序版本
				// #ifdef  MP-WEIXIN
				return wx.getAccountInfoSync().miniProgram.envVersion
				// #endif

				// 根据https判断是不是线上版本
				var str = this.globalData.URL;
				//判断URL地址的正则表达式为:http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
				var Expression = /https:\/\/([\w-]+\.)+[\w-]+(\/[\w- .\/?%&=]*)?/;
				var objExp = new RegExp(Expression);
				if (objExp.test(str) == true) {
					return 'release';
				} else {
					return 'trial';
				}
			},
			// 获取字符串中的query
			getQueryData(url) {
				url = url.substring(url.indexOf("?") + 1);
				const str = url.split("&");
				const url_arr = {};
				for (let i = 0; i < str.length; i++) {
					const sttr = str[i].split("="); // sttr = [aaa,123]
					url_arr[sttr[0]] = sttr[1]; // [aaa:"123"]
				}
				return url_arr;
			},
			// 获取微信公众号openid
			getWxGzhOpenid() {
				//#ifdef H5
				if (isWeiXin()) {
					let sellerNo = this.globalData.sellerNo
					let queryData = this.getQueryData(window.location.href)
					if (queryData.code) {
						https_1.wxcallback({
							code: queryData.code,
							sellerNo,
							type: 2
						}).then(res => {
							if (res.code == 0) {
								if (res.data.length) {
									uni.setStorageSync('wxGzhOpenid', res.data[0].openIdGzh)
								} else {
									uni.setStorageSync('wxGzhOpenid', res.data.openIdGzh)
								}
							} else {
								alert('获取openid失败，状态码：', res.code)
							}

						})
						return
					}
					if (!uni.getStorageSync('wxGzhOpenid') && !queryData.code) {
						https_1.getSerllerConfig({
							sellerNo,
							type: 2
						}).then(res => {
							if (res.code === 0) {
								let appId = res.data.appID
								console.log('获取的商家appId:', appId)
								let redirect_uri = encodeURIComponent(location.href.split('#')[0])
								// let scope = 'snsapi_base' //静态授权
								let scope = 'snsapi_userinfo' //动态授权可以获取头像个人信息

								console.log(
									`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE&connect_redirect=1#wechat_redirect`,
									'链接')
								window.location.href =
									`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirect_uri}&response_type=code&scope=${scope}&state=STATE&connect_redirect=1#wechat_redirect`
							} else {
								// 获取商家信息失败
								uni.showModal({
									title: '提示',
									content: res.msg || '获取商家信息失败',
									success: (res) => {
										if (res.confirm) {
											console.log('comfirm') //点击确定之后执行的代码
										}
									},
								})
							}
						})
					}
				}
				//#endif
			},
			// 小程序内嵌h5方法
			setMiniInH5() {
				// #ifdef H5

				// 厦门公交h5内嵌
				if (this.isxmgjMix()) {
					let token = uni.getStorageSync('token')
					let href = window.location.href
					let code = this.getQueryData(href).code
					let openId = this.getQueryData(href).openId
					if (openId) {
						uni.setStorageSync('openId', openId)
					}
					if (!token) {
						uni.showLoading({
							title: '初始化中',
							mask: true
						})
						console.log(this.getQueryData(href), '这是入参')
						let xmgjToken = this.getQueryData(href).token

						console.log(xmgjToken, 'token')
						if (!xmgjToken) {
							return console.log('没传token')
						}
						uni.setStorageSync('xmgjToken', xmgjToken)
						https_1.xiamengRegisterOrLogin({
							token: xmgjToken,
							sellerNo: this.globalData.sellerNo
						}).then(res => {
							console.log('这是厦门公交的token', res)
							if (res.code == 0) {
								uni.setStorageSync('token', res.data)
								window.location.href = window.location.href
							}
						})
						return
					}
					var script = document.createElement("script");
					script.type = "text/javascript";
					script.src = `https://res.wx.qq.com/open/js/jweixin-1.3.2.js`;
					document.head.appendChild(script);

					// 扫码功能实现
					if (code) {
						scanCodeFn(decodeURIComponent(code))
					}
				}

				// 中核小程序内嵌H5
				if (this.isZsjMiniInH5()) {
					let href = window.location.href
					let code = this.getQueryData(href).scanCodeResult
					let openId = this.getQueryData(href).openid
					if (openId) {
						uni.setStorageSync('openId', openId)
					}

					var script = document.createElement("script");
					script.type = "text/javascript";
					script.src = `https://res.wx.qq.com/open/js/jweixin-1.3.2.js`;
					document.head.appendChild(script);

					// alert(code)
					// 扫码功能实现
					if (code) {
						// alert(href)
						// alert(code)
						// alert(decodeURIComponent(code))
						scanCodeFn(decodeURIComponent(code))
					}
				} else if (this.isCdgj()) {
					// 成都公交-H5授权登录
					// 链接如：https://zccd.cdgjbus.com/h5/cdgj/#/?data=eIis4O+EH/wPxYu8JCOiKeeBut2Y22/aUKImO5d4iItQ1dKAAXnhbyvMGW+Wp64MP2HTjU7jfUuIslvOn0ejoQdAihMF/7ft6qeqeR1e/mSsApbTDO/kztuch5lz0SrioxONKs+kAgJr0skpTEGnuPk7DzilIC6jmkaLshaK4xuOojpxcLXwyuOsm6IOTMwpCezJC6HKsuYhoSLHmhM1VC36ixsgULTBgY748EqW3BVKvKSxsk+NxNm9ppAt8A834K3GPQYdGMGFejxUjaNf+TaB11oju9aPGdIG7ACJZvZ+4Lp5RA1jL0P2fO2WvQQP/AH5ZKo6QUVhfH23vjhs6w==
					this.scriptWeixinSDK()
					this._H5Login({
						urlTokenKey: 'data',
						sellerNoStorageTokenKey: 'cdgjToken',
						H5LoginApi: https_1.CDGJH5Login
					})
				}
				// #endif
			},
			// app内嵌h5方法
			setAppInH5() {
				// #ifdef H5

				if(this.isCYCAPPInH5()){
					// #川逸充app内嵌h5
					// https://gbtrnd.com.cn/h5/jw/#/?pileCode=2023090201_1
					let href = window.location.href
					// 扫码功能实现
					let pileCode = this.getQueryData(href).pileCode
					let thirdCode = this.getQueryData(href).thirdCode || ''
					
					if (href.indexOf('orderSub/pages/orderDetails/orderDetails') >=0 ){
						// 跳转详情页面不错处理逻辑
					} else {
						if(thirdCode){
							uni.setStorageSync('thirdCode',thirdCode)
							if(pileCode){
								let pileCodeArr = pileCode.split('_')
								let pileNo = pileCodeArr[0] || ''
								let gunNo = pileCodeArr[1] || ''
								let code = `http://gbtrnd.com.cn/weixin/#/gunList?pileNo=${pileNo}&gunNo=${gunNo}`
								setTimeout(()=>{
									scanCodeFn(decodeURIComponent(code))
								},1000)
							}
						}
					}
				}
				
				// 中核内嵌h5 app + 小程序
				if (this.isZsjInH5()) {
					// http://172.16.88.57:8080/h5/csht/#/?data=6536011e1798b1335d5ad014df65c33ee030c73016c4f4dffe7b3185fb0aea36a60aa7cddd83dc932fe03e748cf21dccc3d9b32d23135e4501b45c1275524add1fc4a5f1b905391519bf08079dc64f64bc8aa0a9e81f3af39d1277078eca3b89005635a9f66a467cd0a4382effbb77bc7354cf71780e6d0d03b234cdcf5ac415&code=2024012300
					let token = uni.getStorageSync('token')
					let href = window.location.href
					let code = this.getQueryData(href).code

					if (!token) {
						uni.showLoading({
							title: '初始化中',
							mask: true
						})
						console.log(this.getQueryData(href), '这是入参')
						let zsjToken = this.getQueryData(href).data

						console.log(zsjToken, 'zsjToken')
						if (!zsjToken) {
							uni.showToast({
								title: '内嵌未传token',
								icon: 'none'
							})
							return
						}
						uni.setStorageSync('zsjToken', zsjToken)
						https_1.ZSJH5Login({
							data: zsjToken,
							sellerNo: this.globalData.sellerNo
						}).then(res => {
							console.log('这是更换的token', res)
							if (res.code == 0) {
								uni.setStorageSync('token', res.data.Authorization)
								// 内嵌类型 app 、 mini
								uni.setStorageSync('clientType', res.data.clientType)
								window.location.reload()
							}
						})
						return
					} else {
						// 如果有token没有存到类型重新跳转
						if (!uni.getStorageSync('clientType')) {
							uni.removeStorageSync('token')
							window.location.reload()
						}
					}

					// 扫码功能实现
					if (code) {
						// 加定时器，不然首页按钮无法点击
						setTimeout(() => {
							scanCodeFn(decodeURIComponent(code))
						}, 1000)

					}
				}
				// #endif
			},

			/**
			 * H5登录统一处理
			 * @param {Object} options
			 * urlTokenKey：url中甲方的token 键名
			 * sellerNoStorageTokenKey: 需要缓存的甲方 token 键名
			 * H5LoginApi：登录接口
			 */
			_H5Login(options) {
				const {
					urlTokenKey,
					H5LoginApi,
					sellerNoStorageTokenKey
				} = options;

				const href = window.location.href
				console.log('-----_H5Login-href-----', href);
				console.log('解密后的数据', decodeURIComponent(href))
				const token = uni.getStorageSync('token')

				if (!token) {
					console.log('------没有缓存------');
					uni.showLoading({
						title: '初始化中',
						mask: true
					})

					const urlData = this.getQueryData(href)[urlTokenKey] // 内嵌携带的token，用来转换成本项目的token
					if (!urlData) {
						uni.showToast({
							title: '内嵌未传token',
							icon: 'none'
						})
						return
					}

					const authToken = util_1.decodeCharacter(urlData) // 特殊符号处理，否则后端无法解析
					if (sellerNoStorageTokenKey) {
						uni.setStorageSync(sellerNoStorageTokenKey, authToken)
					}

					H5LoginApi({
						data: authToken,
						sellerNo: this.globalData.sellerNo
					}).then(res => {
						if (res.code === 0) {
							let tempToken = res.data
							if (this.isCdgj()) {
								tempToken = res.data.Authorization
							}
							uni.setStorageSync('token', tempToken)
							uni.setStorageSync('clientType', res.data.clientType)
							uni.setStorageSync('openId', res.data.openId)
							uni.setStorageSync('AUTH_OBJ_STR', JSON.stringify(res.data))

							const isH5PayCallback = this.getQueryData(href)['isH5PayCallback']
							if (isH5PayCallback && this.isCdgj()) {
								// 成都公交-H5支付回调重定向处理
								const pageUrl = window.location.hash.replace('#', '')
								uni.navigateTo({
									url: pageUrl,
								})
							} else {
								this.toGunDetail(() => {
									window.location.reload()
								})
							}
						} else {
							uni.showToast({
								title: res.msg,
							})
						}
					})
				} else {
					const isH5PayCallback = this.getQueryData(href)['isH5PayCallback']
					console.log('------有缓存------', isH5PayCallback);
					console.log('------clientType------', uni.getStorageSync('clientType'));
					// 如果有token没有存到类型重新跳转
					if (!uni.getStorageSync('clientType')) {
						uni.removeStorageSync('token')
						window.location.reload()
					} else {
						if (isH5PayCallback && this.isCdgj()) {
							
							// 成都公交-H5支付回调重定向处理
							const pageUrl = window.location.hash.replace('#', '')
							console.log('pageUrl', pageUrl)
							// uni.navigateTo({
							// 	url: pageUrl+'&self_redirect=true',
							// })
						} else {
							this.toGunDetail()
						}
					}
				}

				// 有code 规则，就走识别流程
				const code = this.getQueryData(href).code
				console.log('----_H5Login_code：', code);
				if (code) {
					// 加定时器，不然首页按钮无法点击
					setTimeout(() => {
						scanCodeFn(decodeURIComponent(code))
					}, 1000)
				}
			},

			// 应用微信SDK
			scriptWeixinSDK() {
				// #ifdef H5
				var script = document.createElement("script");
				script.type = "text/javascript";
				script.src = `https://res.wx.qq.com/open/js/jweixin-1.6.0.js`;
				document.head.appendChild(script);
				// #endif
			},

			// 跳转到终端详情页
			toGunDetail(callback) {
				let href = window.location.href
				// 携带枪信息，直接跳转到终端详情页
				const urlGunNo = this.getQueryData(href).gunNo
				const urlPileNo = this.getQueryData(href).pileNo
				if (urlGunNo || urlPileNo) {
					// 如果携带 桩号或枪号，就跳到终端详情页, 对应scanCode 的跳转规则
					if (urlGunNo) {
						// 有枪号-跳转枪详情页
						uni.navigateTo({
							url: `/homeSub/pages/terminal/gunDetail/gunDetail?pileNo=${urlPileNo}&gunNo=${urlGunNo}`
						})
					} else {
						// 没有就跳转桩详情页
						uni.navigateTo({
							url: `/echartsPages/pages/terminal/pileDetail/pileDetail?pileNo=${urlPileNo}`
						})
					}
				} else {
					callback && callback()
				}
			}
		}
	};
</script>
<style lang="scss">
	@import '@/uni_modules/uview-ui/index.scss';
</style>
<style lang="less">
	// 831全局引入修改价格背景样式
	@import "./commin/priceBg.less";

	.container {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
	}

	#pickerCon .arrow-area {
		display: none;
	}

	.uni-popup .uni-popup__wrapper {
		background-color: none;
	}
</style>